package cn.jekun.shop.common.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import cn.jekun.component.base.bean.Page;
import cn.jekun.component.base.exceptions.BusinessException;
import cn.jekun.component.base.validator.annotation.Security;
import cn.jekun.component.core.Constants;
import cn.jekun.shop.web.bean.MyShop;

@Service(MyShopService.BEAN_NAME)
public class MyShopService extends ShopBaseService{

	public static final String BEAN_NAME = "cn.jekun.shop.common.service.MyShopService";
	
	@Override
	public String getNamespace() {
		return "SHOP_MY_SHOP";
	}
	/**
	 * 我的商家
	 * @param userId
	 * @param page
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public JSONObject getMyShops(
			@Security
			String userId,
			Page page) {
		JSONObject jsonObject = new JSONObject();
		//基本验证
		if(StringUtils.isBlank(userId)){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"用户代码不能为空");
		}
		try{
			Map map = new HashMap();
			map.put("userId", userId);
			map.put("concern", "1");//已关注
			List<MyShop> shops = this.list(map,page);
		/*	for(int i=0;i<shops.size();i++){
				
				this.listBySql("select * from ERP_Shop_SPE a left join ERP_SPE_TYPE b ON(a.spe_type_id=b.spe_type_id) where shop_Id='"+shops.get(i)+"'");

			}*/
			//阿昌  minAmount需要显示为字符串
			JsonConfig jsonConfig = new JsonConfig();
			jsonConfig.registerJsonValueProcessor(java.lang.Double.class, new JsonValueProcessor() {
				
				@Override
				public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {
					if (value==null) {
						return "";
					}
					if ("minAmount".equals(key)) {
						return value.toString();
					}
					return value;
				}
				
				@Override
				public Object processArrayValue(Object value, JsonConfig jsonConfig) {
					return value;
				}
			}); 
		    
			
			jsonObject.put("shops", JSONArray.fromObject(shops,jsonConfig));
			jsonObject.put("totals", page.getTotalCount());
			jsonObject.put("pages", page.getPages());
			jsonObject.put("pageSize", page.getPageSize());
			jsonObject.put("currentPage", page.getPageNumber());
			return this.executeRerutn(jsonObject);
		}catch(BusinessException e){
			throw e;
		}catch(Exception e){
			e.printStackTrace();
		}
		return this.executeRerutnFail(jsonObject);
	}
}
